﻿// <copyright file="TotalOpportunities.cs" company="">
// Copyright (c) 2014 All Rights Reserved
// </copyright>
// <author></author>
// <date>3/26/2014 9:19:13 PM</date>
// <summary>Implements the TotalOpportunities Workflow Activity.</summary>
namespace Xrm.Solutions.FrameworkSample.Workflow
{
    using System;
    using System.Activities;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;
    using Xrm.Solutions.FrameworkSample.Common.Entities;
    using System.Linq;
    using Microsoft.Xrm.Sdk.Query;

    /// <summary>
    /// Calculates the total value of an account based on its related opportunities
    /// </summary>
    public class TotalOpportunitiesLateBound : BaseCodeActivity
    {
        #region Input Parameters

        [Input("Account")]
        [ReferenceTarget("account")]
        public InArgument<EntityReference> AccountReference { get; set; }

        #endregion

        #region Output Parameters

        [Output("Total")]
        public OutArgument<Money> Total { get; set; }

        #endregion

        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void ExecuteActivity(CodeActivityContext executionContext)
        {
            base.FailOnException.Set(executionContext, true);
            
            Guid accountId = AccountReference.Get(executionContext).Id;
            decimal total = 0;

            QueryByAttribute qba = new QueryByAttribute("opportunity");
            qba.Attributes.Add("accountid");
            qba.Values.Add(accountId);

            EntityCollection opps = this.OrganizationService.RetrieveMultiple(qba);

            foreach (Entity opp in opps.Entities)
            {
                if (opp.Contains("actualvalue"))
                {
                    Money actual = (Money)opp["actualvalue"];
                    total += actual.Value;
                }
            }

            Total.Set(executionContext, new Money(total));
        }
    }
}